#!/bin/sh
#
# login -- login lab with a specified method
#
# Copyright (C) 2016-2021 Wu Zhangjin <falcon@ruma.tech>
#

TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd)"
. "$TOP_DIR"/tools/docker/config >/dev/null

LOGIN_METHODS="bash vnc ssh webssh webvnc"

verify_login()
{
  method=$1
  match=0
  number=0

  echo $method | grep -q '[a-z]'
  if [ $? -eq 0 ]; then
    for l in $LOGIN_METHODS
    do
      number=`expr $number + 1`

      if [ "$l" = "$method" ]; then
        match=1
        return 0
      fi
    done
  else
    total=`echo "$LOGIN_METHODS " | tr -d -c ' ' | wc -c`
    if [ $method -le $total ]; then
      number=$method
      return 0
    fi
  fi

  return 1
}

login_config()
{
  # List available login methods
  echo "INFO: Please choose one of the login methods:"
  echo
  echo $LOGIN_METHODS | tr ' ' '\n' | nl -v 1
  echo

  # Let user choose one
  read -p 'INFO: Choose the login method: ' method

  [ -z "$method" ] && echo "ERR: No method specified." && exit 1

  number=0
  verify_login $method
  [ $? -ne 0 ] && echo "ERR: No valid method specified." && exit 1

  LOGIN_METHOD=`echo $LOGIN_METHODS | tr ' ' '\n' | head -$number | tail -1`
  echo
  echo $LOGIN_METHODS | tr ' ' '\n' | nl -v 1 | grep " $number"
  echo

  LOGIN=$LOGIN_METHOD

  set_var LOGIN
} # login_config

# Get login method in this order: command argument, environment variable and $LAB_LOGIN configuration
# If the first argument is valid lab, use the second one as login method argument.
if [ -n "$1" ]; then
  LAB=$1
  [ -n "$LAB" ] && get_labs | tr ' ' '\n' | grep -q ^$LAB$
  if [ $? -eq 0 ]; then
    [ -n "$2" ] && LOGIN=$2
  else
    LOGIN=$1
  fi
fi

if [ "$LOGIN" != "list" ]; then
  if [ -n "$LOGIN" ]; then
    # Not login if none specified
    [ "$LOGIN" = "none" ] && exit 0

    verify_login $LOGIN
    if [ $? -ne 0 ]; then
      echo
      echo "ERR: $LOGIN is not valid login method, available methods:"
      echo
      echo "    $LOGIN_METHODS."
      echo
      exit 1
    fi
    set_var LOGIN
  else
    get_var LOGIN none
  fi
fi

# use webvnc by default in non-interactive mode if no LOGIN method configured
if [ "$LOGIN" = "none" -o "$LOGIN" = "list" ]; then
  if [ -t 1 ]; then
    login_config
  else
    LOGIN=webvnc
  fi
  set_var LOGIN
fi

LOGIN_TOOL="$TOP_DIR"/tools/docker/$LOGIN

info_print "Available login methods:"
echo
echo "     $LOGIN_METHODS" | grep -E --color "[^a-z]$LOGIN"
echo
info_print "Switch to another method:"
echo
echo "     $0 LOGIN_METHOD" | sed -e "s%$TOP_DIR/%%g"
echo
info_print "Running '$LOGIN_TOOL'"
echo

# create desktop shortcuts
(get_host; get_browser; create_shortcuts) &

# wait for service running
wait_services $LOGIN

# bash and ssh require a virtual tty console
case $LOGIN in
  bash|ssh)
    if [ -t 1 ]; then
      "$LOGIN_TOOL"
    else
      get_xterm
      [ -n "$XTERM" ] && $XTERM -e "$LOGIN_TOOL"
    fi
    ;;
  *)
     "$LOGIN_TOOL"
     ;;
esac
